using System;
using System.Security.Cryptography;
using System.IO;

namespace Zyg.Security
{
    public class Decryptor
    {
        #region Fields

        /// <summary>
        /// Decrypt transformer
        /// </summary>
        private DecryptTransformer transformer;

        /// <summary>
        /// Initial vector
        /// </summary>
        private byte[] initVec;

        #endregion

        #region Properties

        /// <summary>
        /// Get or set the initial vector
        /// </summary>
        public byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

        #endregion

        #region Methods

        public Decryptor(EncryptionAlgorithm algId)
        {
            transformer = new DecryptTransformer(algId);
        }

        public byte[] Decrypt(byte[] bytesData, byte[] bytesKey)
        {
            MemoryStream memStreamDecryptedData = new MemoryStream();

            transformer.IV = initVec;

            ICryptoTransform transform = transformer.GetCryptoServiceProvider(bytesKey);

            CryptoStream decStream = new CryptoStream(memStreamDecryptedData, transform, CryptoStreamMode.Write);

            try
            {
                decStream.Write(bytesData, 0, bytesData.Length);
            }
            catch (Exception ex)
            {
                throw new Exception("Error occur when trying writing the decrypted data to stream: " + ex.Message);
            }

            decStream.FlushFinalBlock();
            decStream.Close();

            return memStreamDecryptedData.ToArray();
        }

        #endregion

    }
}
